package com.qianli.cashmama.trade.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fqgj.common.api.ApiResponse;
import com.fqgj.common.api.Response;
import com.fqgj.common.utils.CollectionUtils;
import com.fqgj.xjd.user.client.UserService;
import com.fqgj.xjd.user.client.response.User;
import com.google.common.collect.Lists;
import com.qianli.cashmama.trade.application.trade.TradeApplicationServiceImpl;
import com.qianli.cashmama.trade.client.bill.request.BillPayRequest;
import com.qianli.cashmama.trade.client.snapshot.UserTradeSnapshotService;
import com.qianli.cashmama.trade.client.trade.TradeApplicationService;
import com.qianli.cashmama.trade.client.trade.request.CreateTradeRequest;
import com.qianli.cashmama.trade.client.trade.response.CreateTradeResponse;
import com.qianli.cashmama.trade.client.vo.DiscountListVO;
import com.qianli.cashmama.trade.common.mq.MQTradeActionEnum;
import com.qianli.cashmama.trade.common.utils.HttpUtil;
import com.qianli.cashmama.trade.common.utils.MessageManager;
import com.qianli.cashmama.trade.dao.TBillDao;
import com.qianli.cashmama.trade.dao.TTradeDao;
import com.qianli.cashmama.trade.domain.factory.BillBaseDomainFactory;
import com.qianli.cashmama.trade.domain.model.BillAccounting;
import com.qianli.cashmama.trade.domain.model.BillBase;
import com.qianli.cashmama.trade.domain.model.TradeBase;
import com.qianli.cashmama.trade.domain.model.TradeBillDetail;
import com.qianli.cashmama.trade.domain.services.TradeBaseService;
import com.qianli.cashmama.trade.entity.TBillEntity;
import com.qianli.cashmama.trade.entity.TTradeEntity;
import com.qianli.cashmama.trade.integration.notification.message.MessageIntegrationService;
import com.qianli.cashmama.trade.integration.notification.message.dto.BillNoteMsgDto;
import com.qianli.cashmama.trade.integration.product.ProductIntegrationService;
import com.qianli.cashmama.trade.integration.product.dto.ProductDto;
import com.qianli.cashmama.trade.integration.user.UserIntegrationService;
import com.qianli.cashmama.trade.integration.user.dto.UserBaseInfoDto;
import com.qianli.cashmama.trade.mq.MQOpenapiHelpUtils;
import com.qianli.cashmama.trade.openApi.job.RejectJob;
import com.qianli.cashmama.trade.openApi.vendor.inner.InnerSynchronizationHandler;
import com.qianli.cashmama.trade.openApi.vendor.inner.request.InnerPushRequest;
import com.qianli.cashmama.trade.repo.BillAccountingRepository;
import com.qianli.cashmama.trade.repo.BillBaseRepository;
import com.qianli.cashmama.trade.repo.TradeBaseRepository;
import com.qianli.cashmama.trade.repo.TradeBillDetailRepository;
import com.qianli.cashmama.trade.openApi.TradeSynchronizationService;
import com.qianli.cashmama.trade.openApi.enums.MerchantEnum;
import com.qianli.cashmama.trade.openApi.enums.PushStepEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * Created with IntelliJ IDEA.
 * User: sm
 * Date: 2017/9/11
 * Time: 下午4:45
 */
@Controller
public class OkController {

    private static final Logger logger = LoggerFactory.getLogger(OkController.class);

    @Autowired
    private UserIntegrationService userIntegrationService;

    @Autowired
    private TBillDao billDao;

    @Autowired
    private UserTradeSnapshotService userTradeSnapshotService;

    @Autowired
    private MessageIntegrationService messageIntegrationService;

    @Autowired
    private TTradeDao tradeDao;

    @Autowired
    private TradeBaseRepository tradeBaseRepository;

    @Autowired
    private TradeBaseService tradeBaseService;

    @Autowired
    private BillAccountingRepository billAccountingRepository;

    @Autowired
    private BillBaseDomainFactory billBaseDomainFactory;

    @Autowired
    private BillBaseRepository billBaseRepository;

    @Autowired
    private TradeBillDetailRepository tradeBillDetailRepository;

    @Autowired
    private TradeSynchronizationService tradeSynchronizationService;


    @Autowired
    private InnerSynchronizationHandler innerSynchronizationHandler;

    @Autowired
    private TTradeDao tTradeDao;

    @Autowired
    private RejectJob rejectJob;

    @RequestMapping("/ok")
    @ResponseBody
    public String ok() {
        logger.info("== ok ==");
        return "trade,ok";
    }


    @RequestMapping("/reject")
    @ResponseBody
    public String reject() {
        rejectJob.run();
        return "reject";
    }


    @RequestMapping("/push/risk")
    @ResponseBody
    public String pushToRisk() {
        List<TTradeEntity> rupeeGo = tTradeDao.getListByProductCategory("RupeeGo");
        logger.info("== push/risk ==,size:{}", rupeeGo.size());

        int cnt = 0;
        rupeeGo.forEach(entity -> {
            logger.info("== push/risk ==,size:{},id:{}", rupeeGo.size(), entity.getId());
            innerSynchronizationHandler.sendToRiskReview(entity.getTradeNo(), entity.getUserCode(), entity.getIsNewUser() == 1 ? 1 : 2, entity.getProductCategory(), "10001");
        });
        return "push to risk";
    }


    @RequestMapping("/push/{stepCode}")
    @ResponseBody
    public String push(@PathVariable String stepCode) {
        logger.info("== ok ==");
        TTradeEntity tTradeEntity = tradeDao.selectOneByTradeNo("187171595268133455TD");
        InnerPushRequest pushRequest = new InnerPushRequest()
                .setTradeNo(tTradeEntity.getTradeNo())
                .setMerchantCode("tjkj")
                .setStepCode(stepCode.equals("1") ? PushStepEnum.INNER_STEP_ONE.getStepCode() : PushStepEnum.INNER_STEP_TWO.getStepCode())
                .setUserCode(tTradeEntity.getUserCode());
        tradeSynchronizationService.dataSync(MerchantEnum.INNER_SYSTEM, pushRequest);
        return "trade,ok";
    }

    @RequestMapping("/logok")
    @ResponseBody
    public String logok() {

        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");

        logger.info("11111," + HttpUtil.postPageBody("https://cash-pay.cashmama.in/ok", headers, "{}"));
        logger.info("22222," + HttpUtil.postPageBody("https://admin-api.cashmama.in/ok", headers, "{}"));
        logger.info("33333," + HttpUtil.postPageBody("https://app-api.cashmama.in/ok", headers, "{}"));
        logger.info("44444," + HttpUtil.postPageBody("http://149.129.179.143:18080/ok", headers, "{}"));

        logger.info("AA," + HttpUtil.postPageBodyByHttps("https://cash-pay.cashmama.in/ok", headers, "{}"));
        logger.info("BB," + HttpUtil.postPageBodyByHttps("https://admin-api.cashmama.in/ok", headers, "{}"));
        logger.info("CC," + HttpUtil.postPageBodyByHttps("https://app-api.cashmama.in/ok", headers, "{}"));

        logger.info("66666," + HttpUtil.postPageBodyByHttps("http://149.129.179.143:18080/ok", headers, "{}"));

        logger.info("t11111," + com.fqgj.common.utils.HttpUtil.postPageBody("https://cash-pay.cashmama.in/ok", headers, "{}"));
        logger.info("t22222," + com.fqgj.common.utils.HttpUtil.postPageBody("https://admin-api.cashmama.in/ok", headers, "{}"));
        logger.info("t33333," + com.fqgj.common.utils.HttpUtil.postPageBody("https://app-api.cashmama.in/ok", headers, "{}"));
        logger.info("t44444," + com.fqgj.common.utils.HttpUtil.postPageBody("http://149.129.179.143:18080/ok", headers, "{}"));

        return "ok";
    }

    @RequestMapping("/configok")
    @ResponseBody
    public String configok() {
        return "ok,111";
    }

    @RequestMapping("/user/snapshot/create/{tradeNo}")
    @ResponseBody
    public String createUserSnapshot(@PathVariable String tradeNo) {
        userTradeSnapshotService.getTradeUserSnapInfo(tradeNo);
        return "ok";
    }

    @RequestMapping("/sendSms/{tradeNo}/{billNo}")
    @ResponseBody
    public String sendSms(@PathVariable String tradeNo, @PathVariable String billNo) {

        TBillEntity billEntity = billDao.selectOneByBillNo(billNo);
        if (Objects.isNull(billEntity)) {
            return "Query bill failed!";
        }
        TTradeEntity tradeEntity = tradeDao.selectOneByTradeNo(tradeNo);
        if (Objects.isNull(tradeEntity)) {
            return "Query Trade failed!";
        }
        UserBaseInfoDto userBaseInfoDto = userIntegrationService.getUserBaseInfoByUserCode(tradeEntity.getUserCode(), tradeEntity.getProductCategory());
        if (Objects.isNull(userBaseInfoDto)) {
            return "Query User failed!";
        }
        BillNoteMsgDto billNoteMsgDto = new BillNoteMsgDto()
                .setBorrowTotalCapital(tradeEntity.getBorrowTotalCapital().toString())
                .setMobile(userBaseInfoDto.getMobile())
                .setPeriod(billEntity.getCurrentPeriod())
                .setTotalPeriod(tradeEntity.getTotalPeriod())
                .setProuctCode(tradeEntity.getProductCode())
                .setUserCode(tradeEntity.getUserCode())
                .setRepaymentDate(billEntity.getRepaymentDate())
                .setRepaymentCapital(billEntity.getRepaymentCapital().toString());
        return String.valueOf(messageIntegrationService.sendBillNote(billNoteMsgDto));
    }


    //@RequestMapping("/mqTest")
    //@ResponseBody
    //public SendResult mqTest() {
    //    //mq 状态变更通知
    //    TradeFlow tradeFlow = new TradeFlow("21321", "testAction", new Date());
    //    return sendTemplate.syncSend("cashmama_trade_order_status", tradeFlow);
    //}

    @RequestMapping("/test05")
    @ResponseBody
    public String auditCallbackTest() {
        try {
            TradeBase tradeBase = tradeBaseRepository.load("190919TT0213790900");
//        tradeBaseService.highMarkPass(tradeBase);
            return JSON.toJSONString(tradeBase);
        } catch (Exception e) {
            logger.error("==auditCallbackTest==", e);
            return e.getMessage();
        }
    }


    @Autowired
    ProductIntegrationService productIntegrationService;

    @RequestMapping("/test/motan2")
    @ResponseBody
    public String motanTest2() {
        ProductDto productDto = productIntegrationService.getProductInfoByCode("cashmama_new_5000_14");
        logger.info("motan测试" + JSON.toJSONString(productDto));
        return JSON.toJSONString(productDto);
    }

    @RequestMapping("/test/i18n")
    @ResponseBody
    public String i18nTest() {

        return MessageManager.getMsg("test");
    }

    @RequestMapping("/test/account/fix")
    @ResponseBody
    public String func1(@RequestBody JSONObject jsonObject) {
        String payBizNos = jsonObject.getString("payBizNos");
        if (payBizNos == null || payBizNos.length() == 0) {
            return "ok1";
        }
        List<String> payBizNoList = Lists.newArrayList(payBizNos.split(","));
        if (CollectionUtils.isEmpty(payBizNoList)) {
            return "ok2";
        }
        logger.info("待处理还款流水号,payBizNo:{}", JSON.toJSONString(payBizNoList));
        for (String payBizNo : payBizNoList) {
            BillAccounting billAccountingTmp = billAccountingRepository.getBillAccountingByPayBizNo(payBizNo);
            if (billAccountingTmp != null) {
                logger.info("已存在记账流水不处理,payBizNo:{}", billAccountingTmp.getPayBizNo());
                continue;
            }

            TradeBillDetail tradeBillDetail = tradeBillDetailRepository.load(payBizNo);
            if (tradeBillDetail == null) {
                logger.info("还款流水不存在,payBizNo:{}", payBizNo);
                continue;
            }

            BillPayRequest billPayRequest = new BillPayRequest();
            billPayRequest.setTradeNo(tradeBillDetail.getTradeNo());
            billPayRequest.setOperator(tradeBillDetail.getOperator());
            billPayRequest.setBankNo(tradeBillDetail.getBankNo());
            billPayRequest.setPayBizNo(tradeBillDetail.getPayBizNo());
            billPayRequest.setPaidChannel(tradeBillDetail.getPaidChannel());

            DiscountListVO discountListVO = new DiscountListVO();
            discountListVO.setDiscountCapital(tradeBillDetail.getDiscountCapital().toString());

            billPayRequest.setDiscountList(Lists.newArrayList(discountListVO));
            billPayRequest.setDiscountCapital(tradeBillDetail.getDiscountCapital());
            billPayRequest.setPayDate(tradeBillDetail.getAccountedTime());
            billPayRequest.setCapital(tradeBillDetail.getPaidCapital().toString());
            billPayRequest.setUserCode(null);
            billPayRequest.setBillNoList(Lists.newArrayList(tradeBillDetail.getBillNo()));
            billPayRequest.setPaidChannelServiceFee(tradeBillDetail.getChannelServiceFee());
            billPayRequest.setTripleNo("");


            BillBase billBase = billBaseRepository.getBillByBillNo(billPayRequest.getBillNoList().get(0));
            TradeBase tradeBase = tradeBaseRepository.load(billBase.getTradeNo());
            billPayRequest.setUserCode(tradeBase.getUserCode());

            logger.info("调试日期1,billPayRequest:{}", JSON.toJSONString(billPayRequest));

            List<BillAccounting> billAccountingList = billAccountingRepository.getBillAccountingByBillNo(billBase.getBillNo());
            //基于现有的accounting产生一条新的记账
            tradeBillDetail.setBizNo(tradeBillDetail.getBizNo() + "_FIX");

            BillAccounting billAccounting = billBaseDomainFactory.composeBillAccounting(billAccountingList, billBase, tradeBase, billPayRequest, tradeBillDetail);
            logger.info("调试日期2,billAccounting:{}", JSON.toJSONString(billAccounting));
            billAccountingRepository.store(billAccounting);
        }
        return "ok3";
    }


    /*
    @Autowired
    LoanAgainNotificationTask loanAgainNotificationTask;

    @RequestMapping("/execute/LoanAgainNotificationTask")
    @ResponseBody
    public String executeLoanAgainNotificationTask() {
        loanAgainNotificationTask.run();
        return "execute";
    }
    */

    @RequestMapping("/mqtest")
    @ResponseBody
    public ApiResponse mqtest(@RequestBody JSONObject jsonObject) {
        String tradeNo = jsonObject.getString("tradeNo");
        String billNo = jsonObject.getString("billNo");
        MQTradeActionEnum actionEnum = MQTradeActionEnum.getEnum(jsonObject.getString("actionCode"));
        if (billNo != null) {
            JSONObject ext = new JSONObject();
            ext.put("billNo", billNo);
            MQOpenapiHelpUtils.send(tradeNo, actionEnum, ext);
        } else {
            MQOpenapiHelpUtils.send(tradeNo, actionEnum);
        }
        return new ApiResponse();
    }

    @RequestMapping("/to/collction")
    @ResponseBody
    public ApiResponse toCol(@RequestBody JSONObject jsonObject) {


        return new ApiResponse();
    }




}
